/**
 * CookieUtil - 用于操作cookie的工具对象
 * @type {object}
 */
const CookieUtil = {
  /**
   * Cookie的前缀
   * @type {string}
   */
  prefix: 'v3admin',

  /**
   * 设置cookie
   * @param {string} key - cookie的键名
   * @param {string | Boolean | number} value - cookie的值
   * @param {number} [expires] - cookie的过期天数，默认为365天
   * @param {string} [path] - cookie的路径
   * @param {string} [domain] - cookie的域名
   */
  setCookie(key, value, expires = 365, path = '/', domain) {
    const d = new Date()
    d.setTime(d.getTime() + (expires * 24 * 60 * 60 * 1000))
    const expiresStr = `expires=${d.toUTCString()}`
    document.cookie = `${this.prefix}${key}=${value};${expiresStr};path=${path};domain=${domain || ''}`
  },

  /**
   * 获取cookie
   * @param {string} key - cookie的键名
   * @return {string|null} cookie的值或null（如果找不到）
   */
  getCookie(key) {
    const name = `${this.prefix}${key}=`
    const decodedCookie = decodeURIComponent(document.cookie)
    const ca = decodedCookie.split(';')
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i]
      while (c.charAt(0) === ' ') {
        c = c.substring(1)
      }
      if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length)
      }
    }
    return null
  },

  /**
   * 删除cookie
   * @param {string} key - cookie的键名
   * @param {string} [path] - cookie的路径
   * @param {string} [domain] - cookie的域名
   */
  deleteCookie(key, path = '/', domain) {
    document.cookie = `${this.prefix}${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}; domain=${domain || ''}`
  },

  /**
   * 检查cookie是否存在
   * @param {string} key - cookie的键名
   * @return {boolean} 如果cookie存在返回true，否则返回false
   */
  hasCookie(key) {
    return this.getCookie(key) !== null
  },
}

export default CookieUtil
